from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.contrib.auth import get_user_model

User = get_user_model()


class SimpleTokenAuthentication(BaseAuthentication):
    """
    简单的Token认证
    用于开发环境的简化认证
    """
    
    def authenticate(self, request):
        auth_header = request.META.get('HTTP_AUTHORIZATION')
        
        if not auth_header:
            return None
            
        try:
            # 期望格式: "Bearer user_123"
            auth_parts = auth_header.split()
            
            if len(auth_parts) != 2 or auth_parts[0].lower() != 'bearer':
                return None
                
            token = auth_parts[1]
            
            # 解析token格式: user_{user_id}
            if not token.startswith('user_'):
                return None
                
            user_id = token.replace('user_', '')
            
            try:
                user_id = int(user_id)
            except ValueError:
                raise AuthenticationFailed('Invalid token format')
                
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                raise AuthenticationFailed('Invalid token - user not found')
                
            return (user, token)
            
        except Exception as e:
            raise AuthenticationFailed(f'Authentication failed: {str(e)}')
    
    def authenticate_header(self, request):
        return 'Bearer'